package pro.bbs.view.web;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yy.constant.AppConstant;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.log.YYLogKits;
import com.yy.kit.object.YYObjectKits;
import com.yy.kit.string.YYStrKits;
import com.yy.pojo.base.TUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pro.bbs.view.service.TUserLoginRemoteService;
import pro.bbs.view.web.base.BbsCommonController;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 用户登陆以及注册修改密码等操作的controller
 * </p>
 *
 * @author 杨阳
 * @since 2017年10月12日
 */
@Controller
@Api(value = "论坛登陆注册相关的控制类", tags = {"包括用户登陆、用户注册、修改密码、密码找回等跳转"})
public class BbsLoginController extends BbsCommonController {

    @Autowired
    private TUserLoginRemoteService tUserLoginRemoteService;

    /**
     * <p>
     * 用户登陆
     * </p>
     *
     * @param user {@link TUser}用户实体类
     * @return {@link Map<String, Object>}
     */
    @PostMapping("/userLogin")
    @ResponseBody
    @ApiOperation(value = "用户登陆操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体类，包含邮箱及密码", paramType = "query")
    })
    public Map<String, Object> userLogin(TUser user, HttpSession session) {
        Map<String, Object> map = YYMapKits.createHashMap();
        String email = user.getEmail();
        if (YYStrKits.isBlank(email)) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "请输入邮箱!");
            return map;
        }

        String password = user.getPassword();
        if (YYStrKits.isBlank(password)) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "请输入密码!");
            return map;
        }

        map = tUserLoginRemoteService.remoteUserLogin(user);
        //如果是返回true说明成功了，如果不是true,说明失败，那么直接返回
        boolean success = (boolean) map.get("success");
        if (!success) {
            return map;
        }

        //这个地方要注意，我在接口里明明放进去的是TUser对象，但到了这里变成了LinkHashMap不知道为什么
        LinkedHashMap usermap = (LinkedHashMap) map.get("tuser");

        TUser currentUser = YYObjectKits.mapToBean(usermap, TUser.class);

        //将当前用户放到session中
        session.setAttribute(AppConstant.SESSION_KEY, currentUser);

        YYLogKits.info(BbsLoginController.class, "当前用户：{}", currentUser.getName());
        YYLogKits.info(BbsLoginController.class, "用户登陆返回消息：{}", JSONObject.toJSONString(map));

        return map;
    }

    /**
     * <p>
     * 跳转到论坛注册的页面
     * </p>
     *
     * @author 杨阳
     * @since 2017年10月12日
     */
    @GetMapping("/register")
    @ApiOperation(value = "跳转到论坛注册的页面", httpMethod = "GET", tags = {"视图名称：user/reg"})
    public ModelAndView register() {
        return super.goToPageByModelAndView("user/reg", null);
    }

    /**
     * <p>
     * 跳转到论坛登陆的页面
     * </p>
     *
     * @author 杨阳
     * @since 2017年10月12日
     */
    @GetMapping("/login")
    @ApiOperation(value = "跳转到论坛登陆页面", httpMethod = "GET", tags = {"视图名称：user/reg"})
    public ModelAndView login() {
        return super.goToPageByModelAndView("user/login", null);
    }

    /**
     * <p>
     * 退出登陆
     * </p>
     *
     * @return redirect:/登陆页
     * @author 杨阳
     * @since 2017年9月4日17:13:413
     */
    @ApiOperation(value = "退出登陆", httpMethod = "GET", notes = "注销用户session")
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        if (null != session && null != session.getAttribute(AppConstant.SESSION_KEY)) {
            TUser user = (TUser) session.getAttribute(AppConstant.SESSION_KEY);
            YYLogKits.info(BbsLoginController.class, "┌───────────────────────────────────────────────────────────────────────────┐");
            YYLogKits.info(BbsLoginController.class, "├用户：{}注销登陆!", user.getName());
            YYLogKits.info(BbsLoginController.class, "└───────────────────────────────────────────────────────────────────────────┘");
            session.invalidate();
        }
        return "redirect:/";
    }

    /**
     * <p>
     * 用户注册
     * </p>
     *
     * @param user {@link TUser}
     * @return {@link Map<String, Object>}
     */
    @PostMapping("/userRegister")
    @ResponseBody
    @ApiOperation(value = "用户注册", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体类", paramType = "form", dataType = "com.yy.pojo.base.TUser", required = true)
    })
    @HystrixCommand(fallbackMethod = "defaultFallbackMethod")
    public Map<String, Object> userRegister(TUser user) {
        Map<String, Object> map = YYMapKits.createHashMap();
        String email = user.getEmail();
        if (YYStrKits.isBlank(email)) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "请输入邮箱!");
            return map;
        }

        String name = user.getName();
        if (YYStrKits.isBlank(name)) {
            //这里是论坛的用户注册，name是昵称
            map.put("success", Boolean.FALSE);
            map.put("msg", "请输入昵称!");
            return map;
        }

        String password = user.getPassword();
        if (YYStrKits.isBlank(password)) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "请输入密码!");
            return map;
        }
        if (password.length() < 6 || password.length() > 16) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "密码必须是6到16个字符!");
            return map;
        }

        return tUserLoginRemoteService.userRegister(user);
    }

}
